package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author moningxi
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Map<String, Object>> list = orderMapper.turnoverStatistics(beginTime, endTime, Orders.COMPLETED);
        Map<Date, BigDecimal> amountMap = new HashMap<>();
        // 每日金额解析
        for (Map<String, Object> map : list) {
            Date date = (Date) map.get("date");
            BigDecimal amount = (BigDecimal) map.get("amount");
            amountMap.put(date, amount);
        }

        // 处理返回数据
        List<Date> dates = new ArrayList<>(); // 日期集合
        List<BigDecimal> amounts = new ArrayList<>(); // 金额集合
        while (!beginTime.isAfter(endTime)) {
            Date date = Date.valueOf(beginTime.toLocalDate());
            dates.add(date);
            BigDecimal amount = amountMap.get(date) == null ? BigDecimal.ZERO : amountMap.get(date);
            amounts.add(amount);
            beginTime = beginTime.plusDays(1);
        }

        TurnoverReportVO vo = new TurnoverReportVO();
        vo.setDateList(Strings.join(dates, ','));
        vo.setTurnoverList(Strings.join(amounts, ','));
        return vo;
    }

    /**
     * 用户数量统计
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 查询数据
        List<Map<String, Object>> newList = userMapper.newAddSum(beginTime, endTime);

        // 解析数据
        Map<Date, Long> newMap = new HashMap<>();
        for (Map<String, Object> map : newList) {
            Date date = (Date) map.get("date");
            Long sum = (Long) map.get("sum");
            newMap.put(date, sum);
        }

        // 处理返回数据
        List<Long> newAdds = new ArrayList<>(); // 每日新增人数
        List<Long> totalNums = new ArrayList<>(); // 每日总人数
        List<Date> dates = new ArrayList<>();
        while (!beginTime.isAfter(endTime)) {
            Date date = Date.valueOf(beginTime.toLocalDate());
            dates.add(date);
            Long newNum = newMap.get(date) == null ? 0L : newMap.get(date);
            newAdds.add(newNum);
            Long total = userMapper.totalSum(LocalDateTime.of(beginTime.toLocalDate(), LocalTime.MAX));
            totalNums.add(total);
            beginTime = beginTime.plusDays(1);
        }

        return new UserReportVO(Strings.join(dates, ','), Strings.join(totalNums, ','), Strings.join(newAdds, ','));
    }

    /**
     * 订单数量统计
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 查询数据
        List<Map<String, Object>> totalList = orderMapper.totalNum(beginTime, endTime);
        List<Map<String, Object>> validList = orderMapper.validNum(beginTime, endTime, Orders.COMPLETED);

        // 解析数据
        Map<Date, Long> totalMap = new HashMap<>();
        Map<Date, Long> validMap = new HashMap<>();
        int totalOrderCount = 0;
        int validOrderCount = 0;
        for (Map<String, Object> map : totalList) {
            Date date = (Date) map.get("date");
            Long sum = (Long) map.get("num");
            totalOrderCount += sum.intValue();
            totalMap.put(date, sum);
        }
        for (Map<String, Object> map : validList) {
            Date date = (Date) map.get("date");
            Long sum = (Long) map.get("num");
            validOrderCount += sum.intValue();
            validMap.put(date, sum);
        }

        // 处理返回数据
        List<Long> totalNums = new ArrayList<>(); // 每日订单总数
        List<Long> validNums = new ArrayList<>(); // 每日有效订单数
        List<Date> dates = new ArrayList<>();
        while (!beginTime.isAfter(endTime)) {
            Date date = Date.valueOf(beginTime.toLocalDate());
            dates.add(date);
            Long totalNum = totalMap.get(date) == null ? 0L : totalMap.get(date);
            totalNums.add(totalNum);
            Long validNum = validMap.get(date) == null ? 0L : validMap.get(date);
            validNums.add(validNum);
            beginTime = beginTime.plusDays(1);
        }

        double orderCompletionRate = 0.0; // 订单完成率
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(Strings.join(dates, ','))
                .orderCountList(Strings.join(totalNums, ','))
                .validOrderCountList(Strings.join(validNums, ','))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();
    }

    /**
     * 查询销量排名top10
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Map<String, Object>> list = orderDetailMapper.getTop10(beginTime, endTime, Orders.COMPLETED);
        // 解析数据
        List<String> names = new ArrayList<>();
        List<BigDecimal> nums = new ArrayList<>();
        for (Map<String, Object> map : list) {
            String name = (String) map.get("name");
            BigDecimal num = (BigDecimal) map.get("num");
            names.add(name);
            nums.add(num);
        }
        return SalesTop10ReportVO.builder()
                .nameList(Strings.join(names, ','))
                .numberList(Strings.join(nums, ',')).build();
    }

    /**
     * 数据导出
     */
    @Override
    public void export(HttpServletResponse response) {
        LocalDateTime begin = LocalDateTime.now().minusDays(30).with(LocalTime.MIN);
        LocalDateTime end = LocalDateTime.now().minusDays(1).with(LocalTime.MAX);

        try (InputStream is = getClass().getClassLoader().getResourceAsStream("xlsx/运营数据报表模板.xlsx");
             Workbook workbook = new XSSFWorkbook(is);
             ServletOutputStream os = response.getOutputStream()) {

            Sheet sheet = workbook.getSheetAt(0);
            fillSummaryData(sheet, begin, end);
            fillDetailData(sheet, begin, end);

            workbook.write(os);
            os.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 填充概览数据
     */
    private void fillSummaryData(Sheet sheet, LocalDateTime begin, LocalDateTime end) {
        Row row = sheet.getRow(1);
        row.getCell(1).setCellValue("时间：" + begin.toLocalDate() + "至" + end.toLocalDate());

        BusinessDataVO totalBusiness = workspaceService.getBusinessData(begin, end);

        setCellValue(sheet.getRow(3), 2, "￥" + totalBusiness.getTurnover());
        setCellValue(sheet.getRow(3), 4, totalBusiness.getOrderCompletionRate() * 100 + "%");
        setCellValue(sheet.getRow(3), 6, totalBusiness.getNewUsers());
        setCellValue(sheet.getRow(4), 2, totalBusiness.getValidOrderCount());
        setCellValue(sheet.getRow(4), 4, "￥" + totalBusiness.getUnitPrice());
    }

    /**
     * 填充明细数据
     */
    private void fillDetailData(Sheet sheet, LocalDateTime begin, LocalDateTime end) {
        int index = 7;
        while (!begin.isAfter(end)) {
            BusinessDataVO businessData = workspaceService.getBusinessData(begin, begin.with(LocalTime.MAX));
            Row row = sheet.getRow(index++);
            LocalDate localDate = begin.toLocalDate();

            setCellValue(row, 1, String.valueOf(localDate));
            setCellValue(row, 2, "￥" + businessData.getTurnover());
            setCellValue(row, 3, businessData.getValidOrderCount());
            setCellValue(row, 4, businessData.getOrderCompletionRate() * 100 + "%");
            setCellValue(row, 5, "￥" + businessData.getUnitPrice());
            setCellValue(row, 6, businessData.getNewUsers());

            begin = begin.plusDays(1);
        }
    }

    private void setCellValue(Row row, int cellIndex, Object value) {
        System.out.println(row + " " + cellIndex + " " + value);
        Cell cell = row.getCell(cellIndex);
        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        }
    }
}
